package com.atguigu.pojo;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;

import java.math.BigDecimal;
import java.util.List;

public class Dom4jTest {
    @Test
    public void test1() throws Exception {
        SAXReader saxReader = new SAXReader();
        Document doc = saxReader.read("src/books.xml");
        System.out.println(doc);
    }

    /**
     * 读取books.xml文件生成book类
     */
    @Test
    public void test2() throws DocumentException {
        //读取
        SAXReader reader = new SAXReader();
        Document document = reader.read("src/books.xml");
        //获取根元素
        Element rootElement = document.getRootElement();
        //通过根元素获取book标签对象
        List<Element> books = rootElement.elements("book");
        //遍历，把每个对象都转化成类
        for (Element book:
             books) {
            String snValue = book.attributeValue("sn");
            String nameText = book.elementText("name");
            String priceText = book.elementText("price");
            String authorText = book.elementText("author");
            System.out.println(new Book(snValue,nameText, new BigDecimal(priceText),authorText));
        }
    }
}
